/*****************************************************************************
 * HUSONG PROPRIETARY INFORMATION
 * <p/>
 * The information contained herein is proprietary to HUSONG
 * and shall not be reproduced or disclosed in whole or in part
 * or used for any design or manufacture
 * without direct written authorization from HUSONG.
 * <p/>
 * Copyright (c) 2015 by HUSONG.  All rights reserved.
 *****************************************************************************/
package me.send.produce.data.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.send.business.base.jpush.JPush;
import me.send.data.service.bean.FastFoodMap;
import me.send.data.service.bean.ReturnJsonBean;
import me.send.data.service.pojo.ActivitySchoolFastfood;
import me.send.data.service.pojo.ActivitySchoolFastfoodOrder;
import me.send.data.service.pojo.Commaddress;
import me.send.data.service.pojo.OrderProgress;
import me.send.data.service.pojo.Orders;
import me.send.framework.util.DistanceUtil;
import me.send.framework.util.HelperUtil;
import me.send.framework.util.LoggerUtils;
import me.send.produce.data.controller.common.CommonController;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.jpush.api.JPushClient;

import com.alibaba.fastjson.JSON;

/**
 * @author maxmin
 */
@Controller
@RequestMapping(value = "/activity")
public class SchoolActivityController extends CommonController {

	//经纬度
	private final double ALNG = 118.780661;
	private final double ALAT = 32.052565;
	
	private final double DISTANCE = 3;//活动范围
	
	@RequestMapping(value = "/page")
	public String toActivityPage(HttpServletRequest request, Model model,
			Integer userId, Integer advertId, String lng, String lat,
			String cityname,String address) {
		try {
			String date = HelperUtil.getCurrentDate("yyyy-MM-dd");
			int isUsedDiscount = 0;
			List<ActivitySchoolFastfoodOrder> activitySchoolFastfoodOrders = activitySchoolFastfoodOrderService.getActivitySchoolFastfoodOrders(userId, date);
			if (activitySchoolFastfoodOrders!=null&&activitySchoolFastfoodOrders.size()>0) {
				isUsedDiscount=1;
			}
			System.out.println("isUsedDiscount:"+isUsedDiscount);
			Calendar calendar = Calendar.getInstance();
			int i = calendar.get(Calendar.DAY_OF_WEEK);
			int weekday =7;
			if (i!=1) {
				weekday = calendar.get(Calendar.DAY_OF_WEEK)-1;
			}
			List<ActivitySchoolFastfood> list = activitySchoolFastfoodService
					.getActivitySchoolFastfood();
			String listJson = JSON.toJSONString(list);
			String [] wdArr = {"一","二","三","四","五","六","日"};
			String wduper = wdArr[weekday-1];
			
			model.addAttribute("data", listJson);
			model.addAttribute("wduper", wduper);
			model.addAttribute("list", list);
			
			request.getSession().setAttribute("tip", -1);
			request.getSession().setAttribute("commaddress", null);
			request.getSession().setAttribute("commAddressId", null);
			request.getSession().setAttribute("isUsedDiscount", isUsedDiscount);
			request.getSession().setAttribute("fastFoodList", null);
			request.getSession().setAttribute("description", "");
			
			request.getSession().setAttribute("address", address);
			request.getSession().setAttribute("weekday", weekday);
			request.getSession().setAttribute("lng", lng);
			request.getSession().setAttribute("lat", lat);
			request.getSession().setAttribute("cityname", cityname);
			request.getSession().setAttribute("userId", userId);
			request.getSession().setAttribute("advertId", advertId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "activity/school_activity";
	}

	@RequestMapping("/toMakeOrder")
	@ResponseBody
	public ReturnJsonBean toMakeOrder(HttpServletRequest request, Model model,
			Long userId, String description, String maps, Integer advertId) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			if (maps != null) {
				//计算距离
				double lng = Double.valueOf((String)request.getSession().getAttribute("lng"));
				double lat = Double.valueOf((String)request.getSession().getAttribute("lat"));
				double distance = DistanceUtil.distanceByLngLat(ALNG, ALAT, lng, lat);
				System.out.println("到活动的距离："+distance);
				if (distance<=DISTANCE*1000) {
					if (!"".equals(maps)&&maps!=null) {
						System.out.println("有数据");
						List<FastFoodMap> list = JSON.parseArray(maps,FastFoodMap.class);
						request.getSession().setAttribute("fastFoodList", list);
						request.getSession().setAttribute("description", description);
						rb.setCode(ReturnJsonBean.SUCCESS);
						rb.setMessage(ReturnJsonBean.SUCCESS_STR);
					}else {
						System.out.println("没有数据");
						rb.setMessage("请选择商品");
					}
				}else {
					rb.setMessage("配送范围限"+DISTANCE+"公里内，您所在的位置暂不在配送范围内哦~~");
				}
			}
		} catch (Exception e) {
			rb.setMessage("服务器错误");
			e.printStackTrace();
		}
		return rb;
	}

	@RequestMapping("/makeOrder")
	public String makeOrder(HttpServletRequest request, Model model, Long userId) {
		List<Integer> tipList = new ArrayList<Integer>();
		for (int i = 5; i < 11; i++) {
			tipList.add(i);
		}
		model.addAttribute("tipList", tipList);
		return "activity/make_order";
	}

	@RequestMapping("/address")
	public String address(Model model, Integer userId) {
		List<Commaddress> list = commAddressService.getCommAddressList(userId);
		model.addAttribute("userId", userId);
		model.addAttribute("list", list);
		return "activity/address";
	}

	@RequestMapping("/addAddr")
	@ResponseBody
	public ReturnJsonBean addAddr(HttpServletRequest request, Model model,
			Commaddress commaddress) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			commAddressService.addCommAddress(commaddress);
			request.getSession().setAttribute("commaddress", commaddress);
			request.getSession().setAttribute("commAddressId",commaddress.getAddressid());
			request.getSession().setAttribute("sendaddress", commaddress.getText());
			rb.setCode(ReturnJsonBean.SUCCESS);
			rb.setMessage(ReturnJsonBean.SUCCESS_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}

	@RequestMapping("/selectAddrId")
	@ResponseBody
	public ReturnJsonBean selectAddrId(HttpServletRequest request,
			Integer addrId) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			LoggerUtils.info(getClass().getName(), "addrId:" + addrId + "");
			Commaddress commaddress = commAddressService.getCommAddressById(addrId);
			request.getSession().setAttribute("commaddress", commaddress);
			request.getSession().setAttribute("sendaddress", commaddress.getText());
			request.getSession().setAttribute("commAddressId",commaddress.getAddressid());
			rb.setCode(ReturnJsonBean.SUCCESS);
			rb.setMessage(ReturnJsonBean.SUCCESS_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}

	@RequestMapping("/setTip")
	@ResponseBody
	public ReturnJsonBean setTip(HttpServletRequest request,double tip) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			request.getSession().setAttribute("tip", tip);
			rb.setCode(ReturnJsonBean.SUCCESS);
			rb.setMessage(ReturnJsonBean.SUCCESS_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/createOrder")
	@ResponseBody
	public ReturnJsonBean creatOrder(HttpServletRequest request,
			final Orders orders) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			if (orders != null) {

				double countPrice = 0;
				double countDiscountPrice = 0;
				final List<FastFoodMap> list = (List<FastFoodMap>) request.getSession().getAttribute("fastFoodList");
				System.out.println("list 的长度："+list.size());
				Calendar calendar = Calendar.getInstance();
				int wd =7;
				int i=calendar.get(Calendar.DAY_OF_WEEK);
				if (i!=1) {
					wd = calendar.get(Calendar.DAY_OF_WEEK)-1;
				}
				int isUsedDiscount =0;
				if (request.getSession().getAttribute("isUsedDiscount") != null) {
					isUsedDiscount=(Integer) request.getSession().getAttribute("isUsedDiscount");
				}
				final int isUsedDis = isUsedDiscount;
				final int weekday = wd;
				for (FastFoodMap map : list) {
					Long key = map.getKey();
					Integer value = map.getValue();
					ActivitySchoolFastfood fastfood = activitySchoolFastfoodService.getActivitySchoolFastfoodById(key);
					if (fastfood.getWeekday() == weekday) {
						if (isUsedDiscount==0) {
							countDiscountPrice+=fastfood.getPrice()-fastfood.getDiscountPrice();
							isUsedDiscount=1;
						}
					}
					countPrice += fastfood.getPrice() * value;
				}
				orders.setFee(countPrice-countDiscountPrice);
				orders.setDiscount(countDiscountPrice);

				if (request.getSession().getAttribute("userId") != null) {
					orders.setUserid((Integer) request.getSession()
							.getAttribute("userId"));
				}
				if (request.getSession().getAttribute("advertId") != null) {
					orders.setAdvertId((Integer) request.getSession()
							.getAttribute("advertId"));
				}
				if (request.getSession().getAttribute("description") != null) {
					orders.setDescption((String) request.getSession()
							.getAttribute("description"));
				}else{
					rb.setCode(ReturnJsonBean.FAIL);
					rb.setMessage("请选择商品");
					return rb;
				}
				if (request.getSession().getAttribute("commAddressId") != null) {
					orders.setAddressId((Integer) request.getSession()
							.getAttribute("commAddressId"));
				}
				if (request.getSession().getAttribute("lng") != null) {
					orders.setLongitude((String) request.getSession()
							.getAttribute("lng"));
				}
				if (request.getSession().getAttribute("lat") != null) {
					orders.setLatitude((String) request.getSession()
							.getAttribute("lat"));
				}
				if (request.getSession().getAttribute("cityname") != null) {
					orders.setCityname((String) request.getSession()
							.getAttribute("cityname"));
				}
				if (request.getSession().getAttribute("sendaddress") != null) {
					orders.setSendaddress((String) request.getSession()
							.getAttribute("sendaddress"));
				}
				if (request.getSession().getAttribute("address") != null) {
					orders.setAddress((String) request.getSession()
							.getAttribute("address"));
				}
				
				orders.setCreatetime(HelperUtil.getCurrentDate());
				orders.setUpdatetime(HelperUtil.getCurrentDate());
				orders.setStatus(1);
				int rt = ordersService.createOrder(orders);
				if (rt == 0) {
					final int orderid = orders.getOrderid();
					new Thread(new Runnable() {
						public void run() {
							ActivitySchoolFastfoodOrder asfo = null;
							for (FastFoodMap map : list) {
								asfo = new ActivitySchoolFastfoodOrder();
								Long key = map.getKey();
								Integer value = map.getValue();
								ActivitySchoolFastfood fastfood = activitySchoolFastfoodService.getActivitySchoolFastfoodById(key);
								if (fastfood.getWeekday() == weekday) {
									if(isUsedDis==0){
										asfo.setIsDiscount(1);//是折扣价
									}
								}
								asfo.setFastfoodName(fastfood.getName());
								asfo.setOrderid(orderid);
								asfo.setNum(value);
								asfo.setFastfoodId(key);
								asfo.setCreatetime(HelperUtil.getCurrentDate());
								asfo.setPrice(fastfood.getPrice());
								asfo.setDiscountPrice(fastfood.getDiscountPrice());
								if (isUsedDis==0) {
									if (value==1) {
										asfo.setCountDiscountPrice(fastfood.getDiscountPrice() * value);
									}else{
										asfo.setCountDiscountPrice(fastfood.getDiscountPrice()+fastfood.getPrice() * (value-1));
									}
								}else {
									asfo.setCountDiscountPrice(fastfood.getPrice()* value);
								}
								asfo.setCountPrice(fastfood.getPrice()* value);
								activitySchoolFastfoodOrderService.insertActivitSchoolFastfoodOrder(asfo);
							}
							// 推送
							JPushClient client = JPush.getBrokerJPushClient();
							JPush.pushLBSMessageAll(client, "有用户发送新的需求",orders.getLongitude(),orders.getLatitude());
							// 保存进度
							OrderProgress op = new OrderProgress();
							op.setUserMsg("请耐心等待经纪人接单");
							op.setContent("呼单已发布");
							op.setOrderid(orderid);
							op.setOrderStatus(1);
							op.setCreatetime(HelperUtil.getCurrentDate());
							op.setUpdatetime(HelperUtil.getCurrentDate());
							orderProgressService.addOrderProgress(op);
						}
					}).start();
					rb.setCode(ReturnJsonBean.SUCCESS);
					rb.setMessage(ReturnJsonBean.SUCCESS_STR);
				} else if (rt == -1) {
					rb.setMessage("活动已结束");
				} else if (rt == 1) {
					rb.setMessage("出错啦！");
				}
			}else {
				rb.setCode(ReturnJsonBean.FAIL);
				rb.setMessage("当日优惠仅限首单");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}
}
